#! /usr/bin/env python3

import rospy
import threading
from flask import Flask, render_template, request
from a02_task3.msg import car_state
from a02_task3.msg import control_cmd

car_info = "hello world"


def ros_callback(msg):
    global car_info
    car_info = msg
    print('小车控制模式是: ' + car_info.control_mode)
    print('小车基本状态是: ' + car_info.base_state)


threading.Thread(target=lambda: rospy.init_node(
    'scout_info_subsrciber_and_cmd_publisher', disable_signals=True)).start()
rospy.Subscriber('car_state', car_state, ros_callback)
pub = rospy.Publisher('car_control_cmd', control_cmd, queue_size=10)

app = Flask(__name__)


@app.route('/index')
def hello_world():
    global car_info
    return render_template('index.html')

# 信息展示


@app.route('/timeupdate', methods=['GET'])
def timeupdate():
    global car_info
    page = '<h3>前灯状态是: ' + str(car_info.front_light_state) + '</h3>'\
        + '<h3>电池电量是: ' + str(car_info.battery_voltage) + '</h3>' \
        + '<h3>线速度是: ' + str(car_info.linear_velocity) + '</h3>' \
        + '<h3>角速度是: ' + str(car_info.angular_velocity) + '</h3>' \
        + '<h3> 左里程是: ' + str(car_info.left_odometry) + '</h3>' \
        + '<h3> 右里程是: ' + str(car_info.right_odometry) + '</h3>'
    motor_num = 4
    for i in range(0, motor_num):
        page += '第' + str(i) + '个轮子的电机信息:' \
            + '<h3>电机转速是: ' + str(car_info.motor_rpm[i]) + '</h3>' \
            + '<h3>电机电压是: ' + str(car_info.driver_voltage[i]) + '</h3>' \
            + '<h3>电机温度是: ' + str(car_info.motor_temperature[i]) + '</h3>'
    if request.method == 'GET':
        return page


# 控制命令回传
@app.route("/control", methods=['POST', "GET"])
def button_t():
    message = ''
    if request.method == 'GET':
        return render_template('control.html', message='目前还未通过按钮控制小车')

    if request.method == 'POST':
        global car_info
        # 获取被点击的按钮
        bt_a = request.values.get("前进")
        bt_b = request.values.get("后退")
        cmd_info = control_cmd()
        cmd_info.linear_velocity = car_info.linear_velocity + 1
        cmd_info.angular_velocity = car_info.angular_velocity + 1
        pub.publish(cmd_info)
        if (bt_a == 'front'):
            return render_template('control.html', message='小车开始执行前进命令')
        if (bt_b == 'back'):
            return render_template('control.html', message='小车开始执行后退命令')


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
